import axios from 'axios'
import { ElMessage } from 'element-plus'
import {
  BASE_URL,
  NODE_ENV,
  REDIRECT_HOST,
  BASE_API_URL,
  BASE_API_ZIAM_URL,
  BASE_API_ZTNT_URL,
  BASE_API_ZEMD_URL,
  BASE_API_ZDEMD_URL,
  BASE_API_ZFIL_URL,
  BASE_API_ZRFQ_URL,
  BASE_API_ZRFP_URL,
  BASE_API_ZMSG_URL,
  BASE_API_ZCTT_URL,
  BASE_API_ZWKF_URL,
  BASE_API_ZCMS_URL
} from 'config/constant'
import { signActionTime, removeTokenType, removeAccessToken, removeUserInfo, removeTenantId } from 'utils/headerToken'
import { removeCookie } from 'utils/tools'
import Qs from 'qs' // 表单提交 data序列化
// 通讯状态码错误信息提示
const codeMessage = {
  200: '服务器成功返回请求的数据。',
  201: '新建或修改数据成功。',
  202: '一个请求已经进入后台排队（异步任务）。',
  204: '删除数据成功。',
  400: '发出的请求有错误，服务器没有进行新建或修改数据的操作。',
  401: '当前登录信息失效，请重新登录',
  403: '您还没有角色权限，请联系管理员',
  404: '未找到该页面信息，请再刷新一下页面',
  406: '请求的格式不可得。',
  408: '请求失败了',
  410: '请求的资源被永久删除，且不会再得到的。',
  422: '当创建一个对象时，发生一个验证错误。',
  500: '服务器发生错误，请检查服务器。',
  502: '网关错误。',
  503: '服务不可用，服务器暂时过载或维护。',
  504: '网关超时。'
}

// 进度条
import NProgress from 'nprogress'
import 'nprogress/nprogress.css' //nprogress样式

// 初始化一个axios对象
let instance = axios.create({
  baseURL: NODE_ENV === 'development' ? '' : BASE_URL,
  timeout: 30000
})

// 允许携带cookie
axios.defaults.withCredentials = true
axios.defaults.retry = 3
axios.defaults.retryDelay = 200

// 添加请求拦截器
instance.interceptors.request.use(
  (config) => {
    // 前缀+url
    if (config.url.includes('$ziam')) {
      config.url = BASE_API_ZIAM_URL + config.url.split('$ziam')[1]
    } else if (config.url.includes('$ztnt')) {
      config.url = BASE_API_ZTNT_URL + config.url.split('$ztnt')[1]
    } else if (config.url.includes('$zemd')) {
      config.url = BASE_API_ZEMD_URL + config.url.split('$zemd')[1]
    } else if (config.url.includes('$zdemd')) {
      config.url = BASE_API_ZDEMD_URL + config.url.split('$zdemd')[1]
    } else if (config.url.includes('$zfil')) {
      config.url = BASE_API_ZFIL_URL + config.url.split('$zfil')[1]
    } else if (config.url.includes('$zrfq')) {
      config.url = BASE_API_ZRFQ_URL + config.url.split('$zrfq')[1]
    } else if (config.url.includes('$zrfp')) {
      config.url = BASE_API_ZRFP_URL + config.url.split('$zrfp')[1]
    } else if (config.url.includes('$zmsg')) {
      config.url = BASE_API_ZMSG_URL + config.url.split('$zmsg')[1]
    } else if (config.url.includes('$zctt')) {
      config.url = BASE_API_ZCTT_URL + config.url.split('$zctt')[1]
    } else if (config.url.includes('$zwkf')) {
      config.url = BASE_API_ZWKF_URL + config.url.split('$zwkf')[1]
    } else if (config.url.includes('$zcms')) {
      config.url = BASE_API_ZCMS_URL + config.url.split('$zcms')[1]
    } else {
      config.url = BASE_API_URL + config.url
    }
    config.url = config.url.replace(/\$tenantId/g, localStorage.getItem('tenantId'))

    if (config.method === 'delete' || config.method === 'put') {
      config.headers = signActionTime('POSTJSON')
    }
    config.headers['Menu-Global-Code'] = JSON.parse(localStorage.getItem('changeMenuItem'))?.menuGlobalCode
    return config
  },
  (error) => {
    NProgress.done()
    // 对请求错误做些什么
    return Promise.reject(error)
  }
)

// 添加响应拦截器
instance.interceptors.response.use(
  (response) => {
    NProgress.done()
    // 对响应数据做点什么
    if (response.data && response.data.code == '-1') {
      ElMessage({
        showClose: true,
        message: `${response.data.desc}`,
        type: 'error',
        duration: 5000
      })
    }
    response.body = response.data
    return response
  },
  (error) => {
    NProgress.done()
    // 对响应错误做点什么
    for (let key in codeMessage) {
      if (error.response.status == key) {
        ElMessage({
          showClose: true,
          message: `${codeMessage[key]}`,
          type: 'error',
          duration: 5000
        })
        if (key == '401') {
          removeAccessToken()
          removeTokenType()
          removeUserInfo()
          removeTenantId()
          removeCookie('accessToken')
          removeCookie('tokenType')
          // 如果二级域名是北汽 直接跳转\  location.host.includes('batc') &&
          if (window.zcbFun.getSSOTenantId('domain') || window.zcbFun.getSSOTenantId('id')) {
            if (window.location.pathname !== '/' && window.location.pathname !== '/index') {
              localStorage.setItem('redirect_uri', window.location.href)
            }
            window.location.href = window.zcbFun.getSSOTenantId('domain')?.url || window.zcbFun.getSSOTenantId('id')?.url || '/'
            return
          } else {
            window.location.href = `${REDIRECT_HOST}/login?redirect_uri=${encodeURIComponent(window.location.href)}`
          }
        }
      }
    }

    return Promise.reject(error)
  }
)

// 封装get请求方法
export let $get = async (url, params) => {
  let { data } = await instance.get(url, {
    params,
    headers: signActionTime('get')
  })
  return data
}

// 封装post请求方法
export let $post = async (url, params) => {
  let { data } = await instance.post(url, params, {
    headers: signActionTime('POSTJSON')
  })
  return data
}
// 封装postForm请求方法
export let $postForm = async (url, params) => {
  let { data } = await instance.post(url, Qs.stringify(params), {
    headers: signActionTime('POSTFORM')
  })
  return data
}

export let $postFile = async (url, params) => {
  let { data } = await instance.post(url, params, {
    headers: signActionTime('POSTFILE')
  })
  return data
}

// 封装put请求方法
export let $put = async (url, params) => {
  let { data } = await instance.put(url, params, {
    headers: signActionTime('POSTJSON')
  })
  return data
}

// 封装del请求方法
export let $del = async (url, params) => {
  let { data } = await instance.delete(
    url,
    { data: params },
    {
      headers: signActionTime('POSTJSON')
    }
  )
  return data
}

export default instance
